package cn.atzxc.qy.service.impl;

import cn.atzxc.qy.domain.LoginUser;
import cn.atzxc.qy.domain.ResponseResult;
import cn.atzxc.qy.mapper.UserMapper;
import cn.atzxc.qy.service.LoginService;
import cn.atzxc.qy.utils.JwtUtil;
import cn.atzxc.qy.utils.RedisCache;
import cn.atzxc.qy.domain.User;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Value("${wx.online_people_url}")
    private String ONLINE_PEOPLE_URL;

    //小程序的AppID
    @Value("${wx.appId}")
    private String APP_ID;

    //小程序的AppSecret
    @Value("${wx.appSecret}")
    private String SECRET;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        // 自定义认证，获取用户的账号和密码
        /**
         *  把用户名和密码 封装成 authenticationToken 对象
         * 微信一键登录，通过openid进行登录，如果没有则注册
         * 手机号和密码登录：把手机号和密码在数据库中比对
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getPhoneNumber(),user.getPassword());
        System.out.println("authenticationToken:"+authenticationToken);
        // 通过 authenticationManager 进行认证
        // 其中调用了 userDetailsServiceImpl
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用"userid"生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = String.valueOf(loginUser.getUser().getUser_id());
        String jwt = JwtUtil.createJWT(userid);
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的用户信息存入redis  userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);
        return new ResponseResult(200,"登录成功",map);
    }


    /**
     * 微信登陆，通过code获取session_key、openid。
     *     session_key：用于解密 前端wx.getUserProfile(以前是wx.getUserInfo)接口
     *          返回的加密的用户数据，头像、昵称、性别、地区等信息（2022-11，微信已弃用该接口，已无法通过其获取用户信息）。
     *     openid：用户的身份标识，
     *          每个用户在每个公众号或者小程序中都有一个唯一openid，
     *          跨公众号/小程序时openid不相同。若想在公众号、小程序、开放平台等地方使用不同账号，则使用openid作为用户标识。
     *
     * @param code 通过wx.login获取到的用户的code（登录凭证）
     * @return 返回session_key、openid、isSuccess，通过isSuccess是否为true来判断是否成功获取到session_key、openid。
     *         示例：{"session_key":"VtyIGnq9U2E8c95XUm2SeQ==","openid":"o60_YvksCvHRpajcmiLVAUYybXcM","isSuccess":"false"}
     */
    RestTemplate restTemplate = new RestTemplate();
    @Override
    public ResponseResult weixinLogin(String code) {
        String baseUrl =
                ONLINE_PEOPLE_URL + "?appid=" +
                        APP_ID + "&secret=" +
                        SECRET + "&js_code=" + code +
                        "&grant_type=authorization_code";
        ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(baseUrl,byte[].class);
        byte[] body = responseEntity.getBody();
        String json = new String(body);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将字节数组转换为 JSON 对象
            JsonNode jsonNode = objectMapper.readTree(body);
            // 通过 jsonNode 获取字段，例如：
            String sessionKey = jsonNode.get("session_key").asText();
            String openid = jsonNode.get("openid").asText();

            System.out.println("openid="+openid);
            System.out.println("sessionKey="+sessionKey);
            //如果认证通过了，使用"userid"生成一个jwt jwt存入ResponseResult返回
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getOpenid, openid);
            User user = userMapper.selectOne(queryWrapper);
            User usertmp = new User();
            if (Objects.isNull(user)){

                usertmp.setOpenid(openid);
                usertmp.setBalance(0);
                usertmp.setAvatarImage("https://b0.bdstatic.com/0df6c8c7f109aa7b67e7cb15e6f8d025.jpg@h_1280");
                usertmp.setUsername("默认昵称");
                usertmp.setPassword("$2a$10$82fW9/t4eJqv/r65prExDe3K.48FaQJr.n1C7HDeWMAnAVrAZWKwm");
//                usertmp.setRegistrationTime(new Date());
                int insert = userMapper.insert(usertmp);
                if (insert > 0) {
                    user = usertmp;
                    System.out.println("user:"+user);
                }else {
                    throw new RuntimeException("登录失败");
                }
            }
            LoginUser loginUser = new LoginUser(user);
            System.out.println("loginUser为："+loginUser);
            String userid = String.valueOf(loginUser.getUser().getUser_id());
            System.out.println("ID为："+userid);
            String jwt = JwtUtil.createJWT(userid);
            Map<String,String> map = new HashMap<>();
            map.put("token",jwt);
            map.put("json",json);
            //把完整的用户信息存入redis  userid作为key
            redisCache.setCacheObject("login:"+userid,loginUser);
            System.out.println("1231231");
            return new ResponseResult(200, "微信登陆成功", map);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseResult(500, "微信登陆失败", null);
            // 处理转换异常
        }


//        String json = new String(body);
//        System.out.println("返回的结果为："+responseEntity);
//        System.out.println("json:"+json);



    }

    /**
     * 注销登录 消除token
     * @return
     */
    @Override
    public ResponseResult logout() {
        // 因为用户登录后，第一次会经过JWTAuthentication的认证过滤器
        // 如果 携带正确的token,则会把token放入到SecurityContextHolder中

        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = String.valueOf(loginUser.getUser().getUser_id());
        //删除redis中的值
        redisCache.deleteObject("login:"+userid);
        return new ResponseResult(200,"注销成功11");
    }

}
